/*
 * @Author: 王薪林
 * @Date: 2024-10-18 11:51:05
 * @LastEditTime: 2024-10-18 16:18:34
 * @Description: 表格公共操作方法封装
 */

import { reactive, toRefs, ref, computed } from 'vue';

export default function useTable(request, dataCallBack, initParams) {

    const loading = ref(false);

    const state = reactive({
        tableData: [],
        initSearchParams: {},
        searchParams: {},
        totalParams: {},
        pageControl: {
            current: 1,
            pageSize: 10,
            total: 0,
        }
    })

    const page = computed(() => {
        return {
            current: state.pageControl.current,
            pageSize: state.pageControl.pageSize,
        }
    })

    const getTableData = async () => {

        if (!request) {
            return;
        }

        try {
            loading.value = true;

            // 合并初始化参数和搜索参数
            Object.assign(state.totalParams, { ...initParams, ...state.searchParams, ...page.value });

            let { data } = await request(state.totalParams);

            dataCallBack && (data = dataCallBack(data));

            state.tableData = data?.list;

            state.pageControl.total = data?.total;
        } catch (error) {
            console.error(error);
        } finally {
            loading.value = false;
        }
    }

    const handleSizeChange = (pageSize) => {
        state.pageControl.current = 1;
        state.pageControl.pageSize = pageSize;
        getTableData();
    }

    const handleCurrentChange = (current) => {
        state.pageControl.current = current;
        getTableData();
    }

    return {
        loading,
        ...toRefs(state),
        getTableData,
        handleSizeChange,
        handleCurrentChange
    }
}
